<?php

namespace App\Http\Controllers\BuyProcess;

use App\Http\Controllers\Component\MasterResponseController;
use App\Jobs\SendEmail;
use App\Mail\NoticeMail;
use App\Model\Creator;
use Illuminate\Http\Request;
use App\Model\Order;
use Cache;
use Carbon\Carbon;
use DB;
use App\Model\Goods;
use Illuminate\Support\Facades\Redis;
use Webpatser\Uuid\Uuid;
use Auth;

class OrderDetailController extends MasterResponseController
{
    public function __construct()
    {
        $this->middleware('unlogin');
    }

    public function index($id)
    {
        $order = Order::leftJoin('goods_v', 'goods_v.id', 'orders.goods_id')
            ->leftJoin('china_region', 'china_region.town_id', 'orders.town_id')
            ->select(
                'orders.*',
                'china_region.province_name as province',
                'china_region.city_name as city',
                'china_region.county_name as county',
                'china_region.town_name as region',
                'goods_v.name as goods_name',
                'goods_v.author as author',
                'goods_v.price as price',
                'goods_v.size as size',
                'goods_v.genre as genre',
                'goods_v.imgUrl as imgUrl'
            )
            ->where('orders.id', $id)
            ->first();


        $user=Auth::user();
        if ($user->is_sale){
            $myCreator_id=Creator::where('user_id',$user->id)->value('id');
        }else{
            $myCreator_id='';
        }
        $goods_id=$order->goods_id;
        $goods_creator_id=Creator::leftJoin('goods',function ($join) use($goods_id) {
            $join->on('goods.creator_id','=','creators.id')
                ->where('goods.id','=',$goods_id);
        })->value('creators.id');

        $data = array(
            'order' => $order,
            'my_creator_id'=>$myCreator_id,
            'goods_creator_id'=>$goods_creator_id
        );
        return view('buy_process.orderDetail', compact('data'));
    }

    //申请退款
    public function applyRefund(Request $request)
    {
        $key = $request['id'];
        $ttl = 10000;
        //获取Redis实例 并指定连接为redis-order
        $redis = Redis::connection('redis-order');
        $random=Uuid::generate(4); //生成一个UUID作为当前锁的标记
        //$key 加锁的键
        // $random 当前应用锁标记
        //  【px 时间以毫秒计算 ex 时间以秒计算】
        //nx 只在键不存在时，才对键进行设置操作。 SET key value NX 效果等同于 SETNX key value 加锁的关键。
        // xx与nx相反 只在键存在时，才对键进行设置操作。
        //尝试获取锁10000毫秒 即10秒          //尝试加锁10钞钟
        $ok = $redis->set($key, $random,  'px' , $ttl,'nx');
//        $lock = Cache::lock($key, $ttl);
        //如果获取到锁 则进行支付
        if ($ok) {
            //进行更新订单操作
            $time = Carbon::now();
            $order=Order::where('id', $request['id'])->first();
            if ($order->status==1){
                $order->status=100;
                $order->apply_refund_time=$time;
                $order->save();
            }else{
                if ($redis->get($key) == $random) {
                    $redis->del($key);
                }
                return parent::error('此订单卖家已发货，您仅可申请退货退款');
            }

            //释放锁之前对当前锁标记进行判断
            //防止操作在锁时间内未完成 锁自己删除后其他应用获取到锁 从而删除其他应用的锁
            //如果此锁标记与当前应用标记一致则释放锁
            if ($redis->get($key) == $random) {
                $redis->del($key);
            }

            //获取卖家的用户id
            $userId = Goods::leftJoin('creators', 'goods.creator_id', 'creators.id')
                ->select('creators.user_id as user_id')
                ->where('goods.id', $request['goods_id'])->value('user_id');
            //获取卖家的邮箱
            $to = DB::table('users')->where('id',$userId)->value('email');
            $message='您有一笔交易，买家申请退款，请尽快处理！';
            //生成可发送邮件类
            $mail = (new NoticeMail('用户', $message, '退款申请'))
                ->onConnection('redis')
                ->onQueue('emails');
            //将邮件推送到任务队列
            SendEmail::dispatch($to, $mail);
            $message='申请已提交，我们会以邮件方式通知卖家，请等待卖家确认！';
            return parent::successWithData($message,$time->toDateTimeString());
        } else {
            return parent::error('服务器繁忙，请稍后重试！');
        }
    }

    //申请退货退款
    public function applyRefundAndReturn(Request $request)
    {
        $key = $request['id'];
        $ttl = 10000;
        //获取Redis实例
        $redis = Redis::connection('redis-order');
        $random=Uuid::generate(4); //生成一个UUID作为当前锁的标记
        //尝试加锁10钞钟
//        $lock = Cache::lock($key, $ttl);
        $ok = $redis->set($key, $random,  'px' , $ttl,'nx');
        //如果获取到锁 则进行支付
        if ($ok) {
            $time = Carbon::now();
            $order=Order::where('id', $request['id'])->first();
            $order->status=200;
            $order->apply_refund_return_time=$time;
            $order->save();

            //如果锁标记正确则释放锁
            if ($redis->get($key) == $random) {
                $redis->del($key);
            }
            //            $lock->release();

            //获取卖家的用户id
            $userId = Goods::leftJoin('creators', 'goods.creator_id', 'creators.id')
                ->select('creators.user_id as user_id')
                ->where('goods.id', $request['goods_id'])->value('user_id');
            //获取卖家的邮箱
            $to = DB::table('users')->where('id',$userId)->value('email');
            $message='您有一笔交易，买家申请退款退货，请尽快处理！';
            //生成可发送邮件类
            $mail = (new NoticeMail('用户', $message, '退款退货申请'))
                ->onConnection('redis')
                ->onQueue('emails');
            //将邮件推送到任务队列
            SendEmail::dispatch($to, $mail);
            $message='申请已提交，我们会以邮件方式通知卖家，请等待卖家确认！';
            return parent::successWithData($message,$time->toDateTimeString());
        } else {
            return parent::error('服务器繁忙，请稍后重试！');
        }
    }
}
